<template>
  <div>
    <el-dialog title="补增工时" width="40%" :visible.sync="dialogFormVisible">

      <el-form :model="tableData" ref="formInner" size="medium" label-width="120px">

        <el-upload ref="upload" :action="uploadAction" :on-change="fileChange" accept=".xls,.xlsx">
          <el-button size="small" type="primary" icon="el-icon-upload">从文件导入</el-button>
          <div slot="tip" class="el-upload__tip">只能上传不超过 2MB 的.xls,.xlsx文件</div>
        </el-upload>
        <br/>
        <el-table
          data=""
          stripe
          style="width: 100%">
          <el-table-column
            label="姓名"
            width="180">
            <template slot-scope="scope">
              <el-button v-model="scope.name"/>
              <el-select v-model="scope.name" filterable placeholder="选择用户">
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="项目"
            width="180">
            <template slot-scope="scope">
              <el-select v-model="scope.project_name" filterable placeholder="选择项目">
                <el-option
                  v-for="item in options"
                  :key="item.scope.row.name"
                  :label="item.scope.row.name"
                  :value="item.scope.row.name">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="时间">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                              :style="{width: '100%'}" placeholder="请选择日期" clearable></el-date-picker>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog title="批量添加工时" :visible.sync="innerVisible">
          <el-table height="350" :data="tableData" stripe style="width: 100%">
            <el-table-column prop="userName" label="姓名" width="180"/>
            <el-table-column prop="todayPj" label="项目" width="180"/>
            <el-table-column prop="date" label="时间"/>
          </el-table>
          <span slot="footer" class="dialog-footer">
              <el-button @click="innerVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitForm('formInner')">确 定</el-button>
          </span>
        </el-dialog>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import {listUser,} from "@/api/system/user";
import XLSX from 'xlsx'
import {createHourBatch} from "@/api/system/project";
import { Loading } from 'element-ui';

export default {

  data() {
    return {
      innerVisible: false,
      dialogFormVisible: false,
      uploadAction: 'https://jsonplaceholder.typicode.com/posts/',
      userList: [],
      tableData: [],
      hourDate: []
    }
  },
  created() {
    this.getUserList({deptId: 205}, 'userList')
  },
  methods: {
    init() {
    },
    getUserList(param, users) {
      listUser(param).then(
        response => {
          if (response.code == 200) {
            this[users] = response.rows;
          }
        }
      );
    },
    open() {
      // this.getprojectManager();
      this.dialogFormVisible = true;
    },
    closeForm() {
      this.resetForm("ruleForm");
      this.dialogFormVisible = false;
    },
    fileChange(file, fileList) {

      console.log("file", file);
      console.log("fileList", fileList);
      let files = {0: file.raw}
      this.readExcel1(files);
    },
    readExcel1(files) {//表格导入
      console.log(files);
      if (files.length <= 0) {//如果没有文件名
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error('上传格式不正确，请上传xls或者xlsx格式');
        return false;
      }

      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: 'binary'
          });
          const wsname = workbook.SheetNames[0];//取第一张表
          this.tableData = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);//生成json表格内容
          console.log(this.tableData);
          this.innerVisible = true;
          //重写数据
          try {
              this.hourDate = [];
              this.tableData.forEach((item,index,array)=>{
                  this.hourDate.push({
                    userId:item.uid,
                    date:item.date,
                    dangerAct:item.dangerAct,
                    projectHours:[{
                      projectId:item.projectId,
                      hour:item.hour
                    }]
                  })
              }
              )

          } catch (err) {
            console.log(err)
          }

        } catch (e) {
          console.log(e)
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },

    submitForm(formName) {
      var load = Loading.service({ fullscreen: true ,text: '正在提交'});
      this.$refs[formName].validate(valid => {
        if (valid) {
          createHourBatch(this.hourDate).then(res=>{
              this.$notify.success({ title: '插入结果',
                message: '批量补填工时成功',
                showClose: false})
          }).finally(()=>{
            load.close()
          })
        }
      });
      this.tableData = []
      this.hourDate = []
      this.innerVisible = false;
    }


  }
}

</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}

</style>
